package org.newbee.des.zookeeper.queue;

import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.UnsupportedEncodingException;

/**
 * Created by yujie on 2016/10/19.
 */
public class Sub {
    private static ZooKeeper zooKeeper;

    public static void main(String[] args) {
        try {
            zooKeeper = new ZooKeeper("localhost", 2181, watchedEvent -> {
                System.out.println(watchedEvent.getType());
                if (watchedEvent.getType().equals(Watcher.Event.EventType.NodeDataChanged)) {
                    a(watchedEvent.getPath());
                }
            });

            while (true) {
                System.out.println("检测");
                zooKeeper.exists("/zk", true);
                Thread.sleep(5000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void a(String path) {
        zooKeeper.getData(path, false, (i, s, o, bytes, stat) -> {
            try {
                String data = new String(bytes, "utf-8");
                System.out.println("我接收到订阅的消息了 消息是data=" + data);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }, String.valueOf(123));
    }

}
